package com.loeng.module.infra.service.job;

import com.loeng.framework.common.pojo.PageResult;
import com.loeng.framework.common.util.object.BeanUtils;
import com.loeng.module.infra.controller.admin.job.vo.log.JobLogPageReqVO;
import com.loeng.module.infra.controller.admin.job.vo.log.JobLogSaveReqVO;
import com.loeng.module.infra.dal.dataobject.job.JobLogDO;
import com.loeng.module.infra.dal.mysql.job.JobLogMapper;
import com.loeng.module.infra.enums.job.JobLogStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 定时任务日志 Service 实现类
 *
 * @author loeng zhuo
 */
@Service
@Validated
@Slf4j
public class JobLogServiceImpl implements JobLogService {

    @Resource
    private JobLogMapper jobLogMapper;

    /**
     * 创建定时任务日志
     * @param jobId 定时任务编号
     * @param beginTime 开始时间
     * @param jobHandlerName 任务处理器的名字
     * @param jobHandlerParam 任务处理器的参数
     * @param executeIndex 第几次执行
     * @return 定时任务日志编号
     */
    @Override
    public Long createJobLog(Long jobId, LocalDateTime beginTime, String jobHandlerName,
                             String jobHandlerParam, Integer executeIndex) {
        JobLogDO log = JobLogDO.builder().jobId(jobId)
                .handlerName(jobHandlerName).handlerParam(jobHandlerParam)
                .executeIndex(executeIndex).beginTime(beginTime)
                .status(JobLogStatusEnum.RUNNING.getStatus()).build();
        jobLogMapper.insert(log);
        return log.getId();
    }

    /**
     * 更新定时任务日志结果
     * @param logId 定时任务日志编号
     * @param endTime 结束时间
     * @param duration 运行时长
     * @param success 是否成功
     * @param result 结果
     */
    @Override
    @Async
    public void updateJobLogResultAsync(Long logId, LocalDateTime endTime, Integer duration, boolean success, String result) {
        try {
            JobLogDO updateObj = JobLogDO.builder().id(logId).endTime(endTime).duration(duration)
                    .status(success ? JobLogStatusEnum.SUCCESS.getStatus() : JobLogStatusEnum.FAILURE.getStatus())
                    .result(result).build();
            jobLogMapper.updateById(updateObj);
        } catch (Exception ex) {
            log.error("[updateJobLogResultAsync][logId({}) endTime({}) duration({}) success({}) result({})]",
                    logId, endTime, duration, success, result);
        }
    }

    /**
     * 创建定时任务日志
     * @param createReqVO 创建信息
     * @return 定时任务日志编号
     */
    @Override
    public Long createJobLog(JobLogSaveReqVO createReqVO) {
        // 插入
        JobLogDO jobLog = BeanUtils.toBean(createReqVO, JobLogDO.class);
        jobLogMapper.insert(jobLog);
        // 返回
        return jobLog.getId();
    }

    /**
     * 更新定时任务日志
     * @param updateReqVO 更新信息
     */
    @Override
    public void updateJobLog(JobLogSaveReqVO updateReqVO) {
        // 更新
        JobLogDO updateObj = BeanUtils.toBean(updateReqVO, JobLogDO.class);
        jobLogMapper.updateById(updateObj);
    }

    /**
     * 删除定时任务日志
     * @param id 定时任务日志编号
     */
    @Override
    public void deleteJobLog(Long id) {
        // 删除
        jobLogMapper.deleteById(id);
    }

    /**
     * 获得定时任务日志
     * @param id 定时任务日志编号
     * @return 定时任务日志
     */
    @Override
    public JobLogDO getJobLog(Long id) {
        return jobLogMapper.selectById(id);
    }

    /**
     * 获得定时任务日志分页
     * @param pageReqVO 分页查询
     * @return 定时任务日志分页
     */
    @Override
    public PageResult<JobLogDO> getJobLogPage(JobLogPageReqVO pageReqVO) {
        return jobLogMapper.selectPage(pageReqVO);
    }

    /**
     * 清理定时任务日志
     * @param exceedDay 超过多少天
     * @param deleteLimit 删除上限
     * @return 清理数量
     */
    @Override
    @SuppressWarnings("DuplicatedCode")
    public Integer cleanJobLog(Integer exceedDay, Integer deleteLimit) {
        int count = 0;
        LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
        // 循环删除，直到没有满足条件的数据
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            int deleteCount = jobLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
            count += deleteCount;
            // 达到删除预期条数，说明到底了
            if (deleteCount < deleteLimit) {
                break;
            }
        }
        return count;
    }

}